<script setup>
import {useSysUserMutations, useSysUserPage} from "@/composables/sys/user.js"
import {usePagination} from "@/composables/use-pagination.js";
import UserSearch from "@/views/sys/user/components/user-search.vue";
import UserTable from "@/views/sys/user/components/user-table.vue";
import UserDetail from "@/views/sys/user/components/user-detail.vue";
import UserForm from "@/views/sys/user/components/user-form.vue";
import {useMessage} from "naive-ui";
import OrganizationTree from "@/components/organization-tree/index.vue";
import {ref} from "vue";

const sysUserMutations = useSysUserMutations()
const message = useMessage()
const idTemp = ref(null)

const {
  pagination,
  filters,
  queryParams,
  setPage,
  setPageSize,
  resetFilters
} = usePagination({
  username: null,
  nickname: null,
  organizationCode: null,
})

// 查询数据
const {data, isLoading, refetch} = useSysUserPage(queryParams)
// 重置数据
const resetSearch = () => {
  resetFilters()
  refetch()
}

const pageChange = (page) => {
  setPage(page)
  refetch()
}

const pageSizeChange = (pageSize) => {
  setPageSize(pageSize)
  refetch()
}

const searchRef = ref(null)
const formShow = ref(false)


// 新增按钮
const handleAdd = () => {
  formShow.value = true
}

// 批量删除
const handleDeleteBatch = async (checkedRowKeys) => {
  const {code} = await sysUserMutations.removeBatch.mutateAsync(checkedRowKeys)
  if (code === 1) {
    message.success('删除成功')
  }
}
// 删除按钮
const handleDelete = async (id) => {
  const {code} = await sysUserMutations.remove.mutateAsync(id)
  if (code === 1) {
    message.success('删除成功')
  }
}
// 编辑按钮
const handleEdit = async (id) => {
  formShow.value = true
  idTemp.value = id
}
// 关闭表单
const formClosed = () => {
  formShow.value = false
  idTemp.value = null
  refetch()
}
// 选中组织机构
const selectedOrgCodes = (option) => {
  filters.organizationCode = option.code === '-' ? null : option.code
  refetch()
}

</script>

<template>
  <div class="flex">
    <organization-tree
        class="mr-5"
        @on-node-click="selectedOrgCodes"
    />
    <n-space vertical class="flex-1">
      <user-search ref="searchRef" :filters="filters" :refetch="refetch" :reset="resetSearch"/>
      <user-table
          @on-delete="handleDelete"
          @on-edit="handleEdit"
          @on-delete-batch="handleDeleteBatch"
          @on-add="handleAdd"
          :loading="isLoading"
          :data="data?.data?.records || []"
          :page="pagination.page"
          :page-size="pagination.pageSize"
          :item-count="Number(data?.data?.totalRow || 0)"
          @update:page="pageChange"
          @update:page-size="pageSizeChange"
      />
    </n-space>
  </div>
  <user-detail/>
  <user-form
      :show="formShow"
      @close="formClosed"
      :id="idTemp"
  />
</template>

<style scoped>

</style>